//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {

    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView:LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event:egret.Event) {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete(event:RES.ResourceEvent):void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
        RES.loadGroup("preload");
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event:RES.ResourceEvent):void {
        if (event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
            this.createGameScene();
        }
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event:RES.ResourceEvent):void {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event:RES.ResourceEvent):void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress(event:RES.ResourceEvent):void {
        if (event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    private textfield:egret.TextField;

    private stageScroll:StageScroll;

    private myFighter:Airplane;
    private enemyFighters:Airplane[] = [];
    private enemyFightersTimer:egret.Timer = new egret.Timer(1000);

    private myBullets:Bullet[] =[];
    private enemyBullets:Bullet[] =[];


    private scene : MainScene;
    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene():void {

        // var circle:egret.Shape = new egret.Shape();
        // circle.graphics.beginFill(0xff0000, 1);
        // circle.graphics.drawCircle(25, 25, 25);
        // circle.graphics.endFill();
        // this.addChild(circle);

        // var rect:egret.Shape = new egret.Shape();
        // rect.graphics.beginFill(0x00ff00, 1);
        // rect.graphics.drawRect(100, 100, 100, 100);
        // rect.graphics.endFill();
        // this.addChild(rect);

        this.scene = new MainScene();
        this.addChild(this.scene);

        // this.stageScroll = new StageScroll();
        // this.stageScroll.width = this.stage.stageWidth;
        // this.stageScroll.height = this.stage.stageHeight;
        // this.addChild(this.stageScroll);

        // this.stageScroll.stageScrollStart();

        // //
        // this.myFighter = new Airplane(RES.getRes("playerFrame1_png"), 200);
        // this.myFighter.y = this.stage.stageHeight - this.myFighter.height - 50;
        // this.myFighter.x = (this.stage.stageWidth - this.myFighter.width) / 2;
        // this.addChild(this.myFighter);

        // this.myFighter.addEventListener("createBullet", this.createBulletHandler, this);
        // this.myFighter.fire();

        // this.enemyFightersTimer.addEventListener(egret.TimerEvent.TIMER, this.createEnemyFighter, this);
        // this.enemyFightersTimer.start();

        // this.addEventListener(egret.Event.ENTER_FRAME, this.gameViewUpdate, this);
        // this.lastTime = egret.getTimer();
    }

    private createEnemyFighter(et: egret.TimerEvent) {
        var enemyFighter: Airplane = Airplane.produce("p1_png", 1000);
        enemyFighter.x = Math.random() * (this.stage.stageWidth - enemyFighter.width);
        enemyFighter.y = -enemyFighter.height - Math.random() * 300;
        enemyFighter.fire();
        this.addChildAt(enemyFighter, this.numChildren - 1);
        this.enemyFighters.push(enemyFighter);
        enemyFighter.addEventListener("createBullet", this.createBulletHandler, this);
    }

    private createBulletHandler(et:egret.Event) {
        var bullet:Bullet;
        if (et.target == this.myFighter) {
            
            bullet = Bullet.product("b1_png");
            bullet.x = this.myFighter.x + this.myFighter.width / 2 - bullet.width / 2;
            bullet.y = this.myFighter.y - 20;
            this.addChildAt(bullet, this.numChildren - 1 - this.enemyFighters.length);
            this.myBullets.push(bullet);

        } else {
            var fighter:Airplane = et.target;
            bullet = Bullet.product("e1_png");
            bullet.x = fighter.x + fighter.width / 2 - bullet.width / 2;
            bullet.y = fighter.y + 10;
            this.addChildAt(bullet, this.numChildren - 1 - this.enemyFighters.length);
            this.enemyBullets.push(bullet);
        }
    }

    private lastTime:number;

    private gameViewUpdate(et:egret.Event) {

        var now:number = egret.getTimer();
        var fps:number = 1000/(now - this.lastTime);
        this.lastTime = now;
        var speedOffset:number = 60/fps;


        var bullet:Bullet;
        var fighter:Airplane;
        var delArr:any[] = [];


        for (var i = 0; i < this.myBullets.length; i++) {
            bullet = this.myBullets[i];
            bullet.y -= 12 * speedOffset;
            if (bullet.y < -bullet.height) {
                delArr.push(bullet);
            }
        }

        for (var i = 0; i < delArr.length; i++) {
            bullet = delArr[i];
            this.removeChild(bullet);
            Bullet.reclaim(bullet);
            this.myBullets.splice(this.myBullets.indexOf(bullet), 1);
        }

        delArr = [];

        for (var i = 0; i < this.enemyFighters.length; i++) {
            fighter = this.enemyFighters[i];
            fighter.y += 4 * speedOffset;
            if (fighter.y > this.stage.stageHeight) {
                delArr.push(fighter);
            }
        }

        for (var i = 0; i < delArr.length; i++) {
            fighter = delArr[i];
            fighter.removeEventListener("createBullet", this.createBulletHandler, this);
            fighter.stopFire();

            this.removeChild(fighter);
            Airplane.reclaim(fighter);
            this.enemyFighters.splice(this.enemyFighters.indexOf(fighter), 1);
        }

        delArr = [];

        for (var i = 0; i < this.enemyBullets.length; i++) {
            bullet = this.enemyBullets[i];
            bullet.y += 7 * speedOffset;
            if (bullet.y > this.stage.stageHeight) {
                delArr.push(bullet);
            }
        }

        for (var i = 0; i < delArr.length; i++) {
            bullet = delArr[i];
            this.removeChild(bullet);
            Bullet.reclaim(bullet);
            this.enemyBullets.splice(this.enemyBullets.indexOf(bullet), 1);
        }

    }



    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name:string):egret.Bitmap {
        var result = new egret.Bitmap();
        var texture:egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
    
}


